/**
 * 向 product_configs 表添加 membership_tier 字段的迁移脚本
 */

const { sequelize } = require('../config/database');
const { QueryTypes } = require('sequelize');

async function addMembershipTierField() {
  const transaction = await sequelize.transaction();
  
  try {
    console.log('开始添加 membership_tier 字段...');
    
    // 检查字段是否已存在
    const checkFieldExists = await sequelize.query(
      `SELECT COUNT(*) as count 
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'product_configs' 
      AND COLUMN_NAME = 'membership_tier'`,
      { 
        type: QueryTypes.SELECT,
        transaction 
      }
    );
    
    if (checkFieldExists[0].count === 0) {
      // 添加 membership_tier 字段
      await sequelize.query(
        `ALTER TABLE product_configs 
         ADD COLUMN membership_tier INT NULL 
         COMMENT '会员等级：1=一级会员，2=二级会员，3=三级会员，null=非会员产品或通用产品' 
         AFTER tokens_amount`,
        { transaction }
      );
      console.log('成功添加 membership_tier 字段到 product_configs 表');
    } else {
      console.log('membership_tier 字段已存在，无需添加');
    }
    
    await transaction.commit();
    console.log('迁移脚本执行完成!');
    
  } catch (error) {
    await transaction.rollback();
    console.error('迁移脚本执行失败:', error);
  } finally {
    process.exit();
  }
}

// 执行迁移
addMembershipTierField(); 